package com.lijinjiang.listener;

import com.lijinjiang.dao.UserDao;
import com.lijinjiang.entity.User;
import com.lijinjiang.util.MD5Util;
import com.lijinjiang.view.ChangePwdView;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * 个人页面更改密码页面的监听
 */
public class ChangePwdView_Listener implements ActionListener {

    ChangePwdView changePwdView;
    User user;

    public ChangePwdView_Listener(ChangePwdView changePwdView, User user) {
        // TODO Auto-generated constructor stub
        this.changePwdView = changePwdView;
        this.user = user;
    }

    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
        Object event = e.getSource();
        // 获取是否需要输入旧密码
        boolean needOldPwd = changePwdView.getNeedOldPwd();
        // 获取旧密码
        String oldPwd = new String(changePwdView.getOriginalPwd().getPassword());
        String oldPwdMD5 = MD5Util.MD5EncodeUtf8(oldPwd);
        // 获取新密码 和 确认新密码
        String newPwd = new String(changePwdView.getNewPwd().getPassword());
        String confirmPwd = new String(changePwdView.getConfirmPwd().getPassword());
        // 给新密码进行加密
        String newPwdMD5 = MD5Util.MD5EncodeUtf8(newPwd);
        if (event == changePwdView.getSavePwdBtn()) {
            // 如果需要输入旧密码，单独对旧密码验证一次
            if (needOldPwd) {
                if (!user.getPassword().equals(oldPwdMD5)) {
                    JOptionPane.showMessageDialog(null, "原密码输入错误，请确认后重试！",
                            "警告", JOptionPane.WARNING_MESSAGE);
                    return;
                }
            }
            // 其他统一验证
            if (newPwd == null || newPwd.length() == 0) {
                // 为空将密码框设置为红色
                changePwdView.getNewPwd().setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.RED));
                JOptionPane.showMessageDialog(null, "新密码不能为空，请确认后重试！",
                        "警告", JOptionPane.WARNING_MESSAGE);
                return;
            } else if (!newPwd.equals(confirmPwd)) {
                JOptionPane.showMessageDialog(null, "两次输入的新密码不一致，请确认后重试！",
                        "警告", JOptionPane.WARNING_MESSAGE);
                return;
            } else {
                System.out.println("修改密码成功！");
                user.setPassword(newPwdMD5);
                if (!new UserDao().updateUser(user)){
                    JOptionPane.showMessageDialog(null, "密码修改失败！", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }
                JOptionPane.showMessageDialog(null, "密码修改成功！");
                changePwdView.dispose();
            }
        } else {
            if (event == changePwdView.getCloseBtn()) {
                changePwdView.dispose();
            }
        }
    }

}